package com.mjk.common.core.jdbc;


import com.mjk.common.core.jdbc.datasource.DynamicDataSource;
import com.mjk.common.core.redis.datatype.RedisHashUtils;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import java.sql.Connection;

/**
 * jdbc 配置 初始化 sql语句
 * 
 * @author mjk
 *
 */
@Configuration
@ConditionalOnProperty(value="bee.datasource.schema")
public class JdbcConfig implements BeeApplicationListener {
	@Value("${bee.datasource.schema}")
	private String schemaPath;
	
	@Value("${bee.datasource.name}")
	private String dataSourceName ;
	
	private final RedisTemplate redisTemplate;
	
	public static final String SCHEMA_SPLIT = "schema";

	public JdbcConfig(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		
		try {
			ApplicationContext context = event.getApplicationContext();
			DynamicDataSource dataSouce = context.getBean(DynamicDataSource.class);
			DynamicDataSource.setDatabaseType(dataSourceName);
			//Resource[] resources = context.getResources(SCHEMA_PATH);
			ResourcePatternResolver rr = new PathMatchingResourcePatternResolver();
			Resource[] resources = rr.getResources(schemaPath);
			Connection connection= dataSouce.getConnection();
			for (Resource res : resources) {
					if(!RedisHashUtils.exists(redisTemplate, SCHEMA_SPLIT, res.getFilename())) {
						ScriptUtils.executeSqlScript(dataSouce.getConnection(), new EncodedResource(res,"utf-8"));
						RedisHashUtils.set(redisTemplate, SCHEMA_SPLIT, res.getFilename(), "1");
					}
			}

			connection.close();
		} catch (Exception e) {
			BizLogger.error(e.getLocalizedMessage());
		}
	}	

}
